package com.arlen.until.xml;

import com.alibaba.fastjson.JSON;
import com.arlen.common.vo.BaseMessage;
import com.arlen.common.vo.TextMessage;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.*;
import java.util.Map;

public class AnalysisUserMes {
    //处理用户发送信息
    public <T extends BaseMessage> T handleMes(Map mesMao) throws IOException {
        BaseMessage baseMessage = null;
        String type = (String) mesMao.get("MsgType");

        switch (type){
            case "text":
                baseMessage = new TextMessage(mesMao);
                String content = (String) mesMao.get("Content");
                String sendGet = sendGet(content);
                ((TextMessage)baseMessage).setContent(sendGet);
                break;
            case "image":



            default:
                break;
        }

        return (T)baseMessage;
    }



    //官网给的是固定值索性写死
    private static final String qukUrl = "http://api.qingyunke.com/api.php";


    //青云客聊天机器人调用
    private String sendGet(String mes) throws IOException {
        mes = URLEncoder.encode(mes,"utf-8");
        URL url = new URL(qukUrl + "?key=free&appid=0&msg=" + mes);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        if (httpURLConnection.getResponseCode()!= 200){
            throw new IOException();
        }
        InputStream urlConnectionInputStream = httpURLConnection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnectionInputStream));
        String responseMes = reader.readLine();
        if (!StringUtils.isBlank(responseMes)){
            Map<String,Object> map = JSON.parseObject(responseMes, Map.class);
            if (!map.get("result").equals(0)){
                return  null;
            }
            return (String) map.get("content");
        }

        return null;
    }


}
